//
//  LoginViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/14.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit
import PKHUD
import SwiftyJSON
import AlamofireImage

class LoginViewController: BaseViewController {

  // MARK: - IBOutlets
  
  @IBOutlet private weak var wechatButton: UIButton!
  @IBOutlet private weak var weiboButton: UIButton!
  @IBOutlet private weak var qqButton: UIButton!
  
  @IBOutlet weak var emailPhoneTextField: BlackTextField!
  @IBOutlet weak var passwordTextField: BlackTextField!
  
  // MARK: - Private vars
  
  // MARK: - Private methods
  
  private func prepareUI() {
    
    func set(_ button: UIButton, enabledFor forPlatform: UMSocialPlatformType) {
      button.isEnabled = UMSocialManager.default().isInstall(forPlatform)
    }
    
    set(wechatButton, enabledFor: .wechatSession)
    set(weiboButton, enabledFor: .sina)
    set(qqButton, enabledFor: .QQ)
    
    let tapGr = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
    view.addGestureRecognizer(tapGr)
  }
  
  @objc private func hideKeyboard() {
    view.endEditing(true)
  }
  
  private func getUserInfo(from platformType: UMSocialPlatformType) {
    UMSocialManager.default().getUserInfo(with: platformType, currentViewController: nil) { result, error in
      if error == nil {
        if let resp = result as? UMSocialUserInfoResponse {
          
          print("Wechat uid: \(resp.uid ?? "")")
          print("Wechat openid: \(resp.openid ?? "")")
          print("Wechat unionid: \(resp.unionId ?? "")")
          print("Wechat accessToken: \(resp.accessToken ?? "")")
          print("Wechat refreshToken: \(resp.refreshToken ?? "")")
          print("Wechat expiration: \(String(describing: resp.expiration))")
          // 用户信息
          print("Wechat name: \(resp.name ?? "")")
          print("Wechat iconurl: \(resp.iconurl ?? "")")
          print("Wechat gender: \(resp.unionGender ?? "")")
          // 第三方平台SDK源数据
          print("Wechat originalResponse: \(resp.originalResponse ?? "")")
          
          var loginType: User.LoginType = .system
          if platformType == .wechatSession {
            loginType = .wechat
          } else if platformType == .sina {
            loginType = .weibo
          } else if platformType == .QQ {
            loginType = .qq
          }
          self.platformLogin (authID: resp.usid, name: resp.name, loginTyep: loginType, avatar: resp.iconurl)
        } else {
          loggingPrint("No date in UMSocial response")
        }
      } else {
        loggingPrint(error.debugDescription)
      }
    }
  }
  
  private func platformLogin(authID: String, name: String, loginTyep: User.LoginType, avatar: String) {
    HUD.show(.labeledProgress(title: "登录中", subtitle: "请稍后"))
    let deviceUUID = DeviceInfo.current.appUUID
    let iosVersion = DeviceInfo.current.iosVersion
    let modelName = DeviceInfo.current.modelName
    let body: [String : Any] = [
      "auth_id": authID,
      "name": name,
      "login_type": loginTyep.rawValue,
      "avatar": avatar,
      "device": [
        "identifier": deviceUUID,
        "os": iosVersion,
        "model": modelName
      ]
    ]
    API.shared.requestAPI(APIURLStrings.platformLogin, method: .post, body: body, successCallback: { json in
      self.processAfterLoginSuccess(json)
    }) { message, code in
      HUD.flash(.labeledError(title: "登录失败", subtitle: nil), delay: 1.5)
    }
  }
  
  private func processAfterLoginSuccess(_ json: JSON) {
    loggingPrint(json)
    let listenerJSON = json["listener"]
    var gender = User.Gender.unknown
    if let responseGender = User.Gender(rawValue: listenerJSON["gender"].intValue) {
      gender = responseGender
    }
    var user = User (
      identifier: listenerJSON["id"].intValue,
      cellPhone: listenerJSON["cell_phone"].stringValue,
      loginType: User.LoginType.system,
      nickname: listenerJSON["display_name"].stringValue,
      avatar: RemoteImage(dictionary: listenerJSON["avatar"].dictionaryObject!),
      token: json["token"].stringValue,
      gender: gender,
      loginDate: Date(),
        email: listenerJSON["email"].string
    )
    user.isPremium = listenerJSON["is_premium"].boolValue
    UserManager.shared.currentUser = user
    HUD.flash(.labeledSuccess(title: "用户登录成功", subtitle: nil), delay: 1.5)
    if let nav = self.navigationController as? BaseNavigationController {
      if nav.isPresentedModally {
        nav.dismissDelegate?.dismiss(navigationController: nav, completion: nil)
      }
      NotificationCenter.default.post(name: .currentUserUpdated, object: nil)
    }
  }
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    prepareUI()
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  @IBAction func sysLogin() {
    
    guard let emailPhone = emailPhoneTextField.text?.trim(), emailPhone.isValidEmail() || emailPhone.isValidChineseCellPhoneNumber() else {
      let alert = UIAlertController(title: "手机号或Email不正确", message: "请重新输入", cancelTitle: "确定") { _ in
        self.emailPhoneTextField.becomeFirstResponder()
      }
      present(alert, animated: true)
      return
    }
    
    guard let password = passwordTextField.text, password.count > 0 else {
      let alert = UIAlertController(title: "密码不能为空", message: "请重新输入", cancelTitle: "确定") { _ in
        self.passwordTextField.becomeFirstResponder()
      }
      present(alert, animated: true)
      return
    }
    
    HUD.show(.labeledProgress(title: "登录中", subtitle: "请稍后"))
    let deviceUUID = DeviceInfo.current.appUUID
    let iosVersion = DeviceInfo.current.iosVersion
    let modelName = DeviceInfo.current.modelName
    let body: [String : Any] = [
      "email_phone": emailPhone,
      "password_digest": password.md5HexString(),
      "device": [
        "identifier": deviceUUID,
        "os": iosVersion,
        "model": modelName
      ]
    ]
    API.shared.requestAPI(APIURLStrings.systemLogin, method: .post, body: body, successCallback: { json in
//      HUD.flash(.labeledSuccess(title: "登录成功", subtitle: nil), delay: 1.5)
      self.processAfterLoginSuccess(json)
    }) { message, code in
      HUD.flash(.labeledError(title: "登录失败", subtitle: nil), delay: 1.5)
    }
  }
  
  @IBAction func loginViaWechat() {
    getUserInfo(from: .wechatSession)
  }
  
  @IBAction func loginViaWeibo() {
    getUserInfo(from: .sina)
  }
  
  @IBAction func loginViaQQ() {
    getUserInfo(from: .QQ)
  }
  
  @objc private func dismissLogin() {
    if let nav = navigationController as? BaseNavigationController {
      nav.dismissDelegate?.dismiss(navigationController: nav, completion: nil)
    }
  }
  
  // MARK: - Public methods
  
  func addCloseButton() {
    let closeButton = UIBarButtonItem (
      image: UIImage(named: "CloseItem"),
      style: .plain,
      target: self,
      action: #selector(dismissLogin))
    navigationItem.leftBarButtonItem = closeButton
  }
}

// MARK: - UITextFieldDelegate

extension LoginViewController: UITextFieldDelegate {
  func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    if textField == emailPhoneTextField {
      passwordTextField.becomeFirstResponder()
    } else if textField == passwordTextField {
      view.endEditing(true)
    }
    return true
  }
}
